package com.myxfd.superweibo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.myxfd.superweibo.model.TokenInfo;
import com.myxfd.superweibo.model.WeiboInfo;
import com.myxfd.superweibo.services.WeiboService;
import com.myxfd.superweibo.web.BrowserSupport;
import com.myxfd.superweibo.web.MyWebViewClient;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity implements BrowserSupport {

    //    public static final String APP_SECRET="eeb0fcf7ad46de637da4dbbd04b07dd9";
    //    public static final String APP_KEY="2781148230";
    public static final String APP_KEY = "1588832249";
    public static final String APP_SECRET = "77a35865ad9b76e6067519efd2f54293";

    private static final String TAG = "MainActivity";
    private WebView mWebView;
    private WeiboService mWeiboService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = (WebView) findViewById(R.id.main_web_view);

        mWebView.setWebViewClient(new MyWebViewClient(this));

        //TODO: 部分网址需要浏览器支持, 打开 JavaScript
        WebSettings settings = mWebView.getSettings();
        //开启Js支持
        settings.setJavaScriptEnabled(true);
        //在网页中显示 放大缩小 (通常不要使用)
        settings.setDisplayZoomControls(true);
        //允许访问Access目录
        settings.setAllowFileAccess(true);

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        String str = "https://api.weibo.com/oauth2/authorize?client_id=" + APP_KEY + "&redirect_uri=https://api.weibo.com/oauth2/default.html";
        mWebView.loadUrl(str);

        initWeiboService();
    }

    private void initWeiboService() {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("https://api.weibo.com/");
        //基本类型
        builder.addConverterFactory(ScalarsConverterFactory.create());
        //Gson格式
        builder.addConverterFactory(GsonConverterFactory.create());
        Retrofit retrofit = builder.build();
        mWeiboService = retrofit.create(WeiboService.class);
    }


    @Override
    public void loadAppUrl(WebView view, String url) {
        Log.d(TAG, "loadAppUrl: url => " + url);
        Pattern p = Pattern.compile("(.*)code=(.*)");
        Matcher m = p.matcher(url);
        if (m.find()) {
            String code = m.group(2);
            Log.d(TAG, "loadAppUrl: code = " + code);

            Call<TokenInfo> callToken = mWeiboService.getToken(
                    APP_KEY, APP_SECRET,
                    "authorization_code",
                    code,
                    "https://api.weibo.com/oauth2/default.html"
            );
            callToken.enqueue(new Callback<TokenInfo>() {
                @Override
                public void onResponse(Call<TokenInfo> call, Response<TokenInfo> response) {
                    if (response.isSuccessful()) {

                        TokenInfo info = response.body();
                        String token = info.getAccess_token();
                        Log.d(TAG, "onResponse: token => " + token);
                        //得到token之后获取JSON
                        mWeiboService.getWeiboInfo(token).enqueue(new Callback<WeiboInfo>() {
                            @Override
                            public void onResponse(Call<WeiboInfo> call, Response<WeiboInfo> response) {
                                if (response.isSuccessful()) {
                                    WeiboInfo info = response.body();
                                    List<WeiboInfo.Status> statuses = info.getStatuses();
                                    for (WeiboInfo.Status bean : statuses) {
                                        String text = bean.getText();
                                        Log.d(TAG, "onResponse: text" + text);
                                    }
                                } else {
                                    Log.d(TAG, "onResponse: 获取JSON失败");
                                }
                            }

                            @Override
                            public void onFailure(Call<WeiboInfo> call, Throwable t) {
                                t.printStackTrace();
                            }
                        });


                    } else {
                        Log.d(TAG, "onResponse: 返回失败");
                    }
                }

                @Override
                public void onFailure(Call<TokenInfo> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }

    }
}
